package com.qy.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qy.dto.JsonPackageInfo;
import com.qy.dto.PackageDataDTO;
import com.qy.dto.PromotionDataDTO;
import com.qy.entity.PackageInfo;
import com.qy.entity.PackageInfoVO;
import com.qy.entity.PromotionPolicy;
import com.qy.entity.UserCommProfile;
import com.qy.service.ITaocanService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping("/taocan")
@RestController
public class TaocanController {

    @Resource
    private ITaocanService taocanService;

    @GetMapping(value = "/listTaocan")
    @Operation(summary = "套餐列表", description = "套餐列表")
    public List<PackageInfoVO> listTaocan() {
        return taocanService.listTaocan();
    }

    @GetMapping(value = "/listUser")
    @Operation(summary = "用户列表", description = "用户列表")
    public List<UserCommProfile> listUser() {
        return taocanService.listUser();
    }
    
    @GetMapping(value = "/listPromotions")
    @Operation(summary = "优惠政策列表", description = "获取所有优惠政策信息")
    public List<PromotionPolicy> listPromotions() {
        return taocanService.listPromotions();
    }
    
    @PostMapping(value = "/editPromotion")
    @Operation(summary = "编辑优惠政策", description = "编辑现有的优惠政策信息")
    public Map<String, Object> editPromotion(@RequestBody PromotionPolicy promotionPolicy) {
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("收到编辑优惠政策请求：{}", promotionPolicy);
            boolean success = taocanService.editPromotion(promotionPolicy);
            if (success) {
                result.put("code", 200);
                result.put("message", "编辑优惠政策成功");
                result.put("data", promotionPolicy);
            } else {
                result.put("code", 500);
                result.put("message", "编辑优惠政策失败");
            }
        } catch (Exception e) {
            log.error("编辑优惠政策异常：{}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "编辑优惠政策异常：" + e.getMessage());
        }
        return result;
    }
    
    @DeleteMapping(value = "/deletePromotion/{promotionId}")
    @Operation(summary = "删除优惠政策", description = "删除指定的优惠政策")
    public Map<String, Object> deletePromotion(@PathVariable("promotionId") String promotionId) {
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("收到删除优惠政策请求：优惠ID={}", promotionId);
            boolean success = taocanService.deletePromotion(promotionId);
            if (success) {
                result.put("code", 200);
                result.put("message", "删除优惠政策成功");
            } else {
                result.put("code", 500);
                result.put("message", "删除优惠政策失败");
            }
        } catch (Exception e) {
            log.error("删除优惠政策异常：{}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "删除优惠政策异常：" + e.getMessage());
        }
        return result;
    }
    
    @GetMapping(value = "/getUserTypeCategories")
    @Operation(summary = "用户群体分类", description = "获取所有用户群体分类数据")
    public Map<String, Object> getUserTypeCategories() {
        try {
            log.info("获取用户群体分类数据");
            return taocanService.getUserTypeCategories();
        } catch (Exception e) {
            log.error("获取用户群体分类数据异常：{}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取用户群体分类数据异常：" + e.getMessage());
            return result;
        }
    }
    
    @GetMapping(value = "/getPriceRangeCategories")
    @Operation(summary = "价格区间分类", description = "获取所有价格区间分类数据")
    public Map<String, Object> getPriceRangeCategories() {
        try {
            log.info("获取价格区间分类数据");
            return taocanService.getPriceRangeCategories();
        } catch (Exception e) {
            log.error("获取价格区间分类数据异常：{}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取价格区间分类数据异常：" + e.getMessage());
            return result;
        }
    }

    @PostMapping(value = "/addTaocan")
    @Operation(summary = "添加套餐", description = "添加新的套餐信息")
    public Map<String, Object> addTaocan(@RequestBody PackageInfo packageInfo) {
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("收到添加套餐请求：{}", packageInfo);
            boolean success = taocanService.addTaocan(packageInfo);
            if (success) {
                result.put("code", 200);
                result.put("message", "添加套餐成功");
                result.put("data", packageInfo);
            } else {
                result.put("code", 500);
                result.put("message", "添加套餐失败");
            }
        } catch (Exception e) {
            log.error("添加套餐异常：{}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "添加套餐异常：" + e.getMessage());
        }
        return result;
    }
    
    @PostMapping(value = "/editTaocan")
    @Operation(summary = "编辑套餐", description = "编辑现有的套餐信息")
    public Map<String, Object> editTaocan(@RequestBody PackageInfo packageInfo) {
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("收到编辑套餐请求：{}", packageInfo);
            boolean success = taocanService.editTaocan(packageInfo);
            if (success) {
                result.put("code", 200);
                result.put("message", "编辑套餐成功");
                result.put("data", packageInfo);
            } else {
                result.put("code", 500);
                result.put("message", "编辑套餐失败");
            }
        } catch (Exception e) {
            log.error("编辑套餐异常：{}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "编辑套餐异常：" + e.getMessage());
        }
        return result;
    }
    
    @PostMapping(value = "/importPackages")
    @Operation(summary = "导入套餐数据", description = "从JSON文件导入套餐数据到数据库")
    public Map<String, Object> importPackages(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("收到导入套餐数据请求");
            
            // 检查文件是否为空
            if (file.isEmpty()) {
                result.put("code", 400);
                result.put("message", "上传的文件为空");
                return result;
            }
            
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || (!contentType.equals("application/json") && !contentType.contains("text/plain"))) {
                result.put("code", 400);
                result.put("message", "请上传JSON格式的文件");
                return result;
            }
            
            // 解析JSON文件
            ObjectMapper mapper = new ObjectMapper();
            PackageDataDTO packageData = mapper.readValue(file.getInputStream(), PackageDataDTO.class);
            
            // 检查解析结果
            if (packageData.getPackages() == null || packageData.getPackages().isEmpty()) {
                result.put("code", 400);
                result.put("message", "JSON文件格式不符合要求，缺少packages数组");
                return result;
            }
            
            // 处理套餐数据
            int importedCount = 0;
            int skippedCount = 0;
            
            for (JsonPackageInfo jsonPackage : packageData.getPackages()) {
                // 检查数据是否存在
                boolean exists = taocanService.packageExists(jsonPackage.getPackageId());
                if (exists) {
                    skippedCount++;
                    log.info("套餐{}已存在，跳过导入", jsonPackage.getPackageId());
                } else {
                    // 将JsonPackageInfo转换为PackageInfo实体
                    PackageInfo pkg = new PackageInfo();
                    // 复制基本属性
                    BeanUtils.copyProperties(jsonPackage, pkg);
                    
                    // 处理数组类型字段，转换为逗号分隔的字符串
                    if (jsonPackage.getFeatures() != null) {
                        pkg.setFeatures(String.join(",", jsonPackage.getFeatures()));
                    }
                    if (jsonPackage.getTargetUsers() != null) {
                        pkg.setTargetUsers(String.join(",", jsonPackage.getTargetUsers()));
                    }
                    
                    // 保存套餐数据
                    boolean success = taocanService.addTaocan(pkg);
                    if (success) {
                        importedCount++;
                        log.info("套餐{}导入成功", jsonPackage.getPackageId());
                    } else {
                        skippedCount++;
                        log.error("套餐{}导入失败", jsonPackage.getPackageId());
                    }
                }
            }

            // 处理优惠政策数据（如果有）
            int importedPromotionCount = 0;
            int skippedPromotionCount = 0;

            if (packageData.getPromotions() != null && !packageData.getPromotions().isEmpty()) {
                for (PromotionDataDTO promotion : packageData.getPromotions()) {
                    // 检查优惠政策是否已存在
                    boolean exists = taocanService.promotionExists(promotion.getPromotionId());
                    if (exists) {
                        skippedPromotionCount++;
                        log.info("优惠政策{}已存在，跳过导入", promotion.getPromotionId());
                    } else {
                        // 将PromotionDataDTO转换为PromotionPolicy
                        PromotionPolicy promotionPolicy = new PromotionPolicy();
                        BeanUtils.copyProperties(promotion, promotionPolicy);

                        // 转换数组为逗号分隔的字符串
                        if (promotion.getTargetPackages() instanceof List) {
                            promotionPolicy.setTargetPackages(String.join(",", (List<String>) promotion.getTargetPackages()));
                        }
                        if (promotion.getEligibility() instanceof List) {
                            promotionPolicy.setEligibility(String.join(",", (List<String>) promotion.getEligibility()));
                        }

                        // 保存优惠政策数据
                        boolean success = taocanService.addPromotion(promotionPolicy);
                        if (success) {
                            importedPromotionCount++;
                            log.info("优惠政策{}导入成功", promotion.getPromotionId());
                        } else {
                            skippedPromotionCount++;
                            log.error("优惠政策{}导入失败", promotion.getPromotionId());
                        }
                    }
                }
            }

            result.put("code", 200);
            result.put("message", "数据导入完成");
            result.put("importedCount", importedCount);
            result.put("skippedCount", skippedCount);
            result.put("importedPromotionCount", importedPromotionCount);
            result.put("skippedPromotionCount", skippedPromotionCount);

        } catch (IOException e) {
            log.error("解析JSON文件异常：{}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "解析JSON文件异常：" + e.getMessage());
        } catch (Exception e) {
            log.error("导入套餐数据异常：{}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "导入套餐数据异常：" + e.getMessage());
        }
        
        return result;
    }
}
